/*
 * Copyright (c) 2017 Solidwang. All Rights Reserved
 */
package com.solid4j.auth.controller;

import com.alibaba.fastjson.JSON;

import com.solid4j.auth.bean.Config;
import com.solid4j.auth.bean.Items;
import com.solid4j.auth.model.Menu;
import com.solid4j.auth.model.Privilege;
import com.solid4j.auth.model.Role;
import com.solid4j.auth.model.User;
import com.solid4j.auth.service.MenuService;
import com.solid4j.auth.service.UserService;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: solidwang
 * @date: 17/5/4
 */
@Controller
public class LoginController {

    @Resource
    private UserService userService;

    @Resource
    private MenuService menuService;

    @RequestMapping("/login")
    public String login(User user, Model model, HttpServletRequest request, HttpServletResponse response) {
        //判断用户名和密码是否为空
        String passport = user.getPassport();
        String password = user.getPassword();
        if (StringUtils.isEmpty(passport) || StringUtils.isEmpty(password)) {
            return "redirect:/login.jsp";
        }

        //判断用户是否存在
        User userInfo = userService.getByPassport(passport);
        if (userInfo == null) {
            return "redirect:/login.jsp";
        }

        //查询用户所拥有的菜单权限
        Set<Role> rolesSet = userInfo.getRoles();
        Set<Privilege> privilegesSet = new LinkedHashSet<>();
        Set<Menu> menusSet = new LinkedHashSet<>();
        for(Role role : rolesSet) {
            privilegesSet.addAll(role.getPrivileges());
        }
        for(Privilege privilege : privilegesSet) {
            menusSet.addAll(privilege.getMenus());
        }

        //对用户拥有的菜单进行排序
        List<Menu> menus = new ArrayList<Menu>(menusSet);
        Collections.sort(menus, new Comparator<Menu>() {
            public int compare(Menu arg0, Menu arg1) {
                return arg0.getMenuOrder().compareTo(arg1.getMenuOrder());
            }
        });

        //用户拥有的一级菜单
        List<Menu> firstMenus = new ArrayList<Menu>();
        for(Menu menu : menus) {
            if (menu.getParentId() == 0) {
                firstMenus.add(menu);
            }
        }

        //用户拥有的二级菜单json
        List<Config> configs = new ArrayList<Config>();
        for(Menu firstMenu : firstMenus) {
            Config config = new Config();
            config.setId(String.valueOf(firstMenu.getId()));
            List<Items> itemsList = new ArrayList<>();
            List<com.solid4j.auth.bean.Menu> menuList = new ArrayList<>();
            for(Menu secondMenu : menus) {
                if(secondMenu.getParentId()==0 || secondMenu.getParentId()!=firstMenu.getId()) continue;
                Items items = new Items();
                items.setId(String.valueOf(secondMenu.getId()));
                items.setText(secondMenu.getMenuName());
                items.setHref(secondMenu.getMenuUrl());
                itemsList.add(items);
            }
            // 如果没有二级菜单直接跳过
            if (itemsList.size() == 0) continue;
            com.solid4j.auth.bean.Menu menu = new com.solid4j.auth.bean.Menu();
            menu.setText(firstMenu.getMenuName());
            menu.setItems(itemsList);
            menuList.add(menu);
            config.setMenu(menuList);
            config.setHomePage(String.valueOf(itemsList.get(0).getId()));
            configs.add(config);
        }
        String data = JSON.toJSONString(configs);
        model.addAttribute("userInfo", userInfo);
        model.addAttribute("data", data);
        model.addAttribute("firstMenus", firstMenus);
        return "/index";
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request) {
        // session失效
        request.getSession().invalidate();
        return "redirect:/login.jsp";
    }
}
